<template>
  <div class="home">
    <div class="detail_box">
      <!-- 菜单 -->
      <div class="tab_menu">
        <div>
          <span v-for="(item,index) in menus" :class="{'choose':index===mIndex}" @click="chooseTab(index,item.id)" :key="index">{{item.name}}</span>
        </div>
      </div>
      <!-- 操作 -->
      <div class="operate_box">
        <div class="item_box">
          <div class="operate_item" v-if="user&&user.type!==3">
            <label>仓库：</label>
            <el-select
              filterable
              v-model="warehouseId"
              placeholder="请选择仓库">
              <el-option label="全部" :value="''"></el-option>
              <el-option
                v-for="(item,index) in warehouseOption"
                :key="index"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>

<!--          <div class="operate_item">-->
<!--            <label>转单：</label>-->
<!--            <el-select-->
<!--              filterable-->
<!--              v-model="isReplace"-->
<!--              placeholder="请选择">-->
<!--              <el-option label="全部" :value="''"></el-option>-->
<!--              <el-option-->
<!--                v-for="(item,index) in replaceOption"-->
<!--                :key="index"-->
<!--                :label="item.name"-->
<!--                :value="item.id">-->
<!--              </el-option>-->
<!--            </el-select>-->
<!--          </div>-->

          <div class="operate_item">
            <label>退货单号：</label>
            <el-input type="text" placeholder="请输入退货单号" v-model="returnNo" clearable></el-input>
          </div>

          <div class="operate_item" v-if="!$route.query.userId">
            <label>用户：</label>
            <userSelect @listenToUser="getUserId" :uId="usersId"/>
          </div>
          <div class="operate_item">
            <label>时间：</label>
            <el-date-picker
              v-model="proDate"
              type="datetimerange"
              align="right"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              clearable
              :default-time="['00:00:00', '23:59:59']">
            </el-date-picker>
          </div>
          <div class="operate_item">
            <span class="operate_btn search_btn" @click="getTableInfo(1)">查询</span>
            <span class="operate_btn reset_btn" @click="resetTable">重置</span>
          </div>
        </div>
<!--        <div class="btn_box">-->
<!--          <span class="operate_btn search_btn" @click="createOrder">生成退货单</span>-->
<!--        </div>-->
      </div>
      <!-- 表格 -->
      <div class="flex_box">
        <div class="detail_part" :class="{'left_box':isPop}">
          <div class="table_box">
            <el-table
              border
              height="620"
              v-loading="loading"
              :header-cell-style="tableHeader"
              ref="multipleTable"
              :data="tableInfo"
              tooltip-effect="dark"
              highlight-current-row
              style="width: 150%;">
              <el-table-column
                width="160"
                sortable
                prop="createTime"
                label="创建时间">
                <template slot-scope="scope">
                  <p style="text-align: left">{{ formatTime(scope.row.createTime) }}</p>
                </template>
              </el-table-column>

              <el-table-column
                prop="name"
                width="170"
                label="用户名">
                <template slot-scope="scope">{{ scope.row.wxName ? scope.row.wxName : '——' }}{{`(ID:${scope.row.userId})`}}</template>
              </el-table-column>

              <el-table-column
                prop="returnNo"
                width="220"
                label="退货单号">
              </el-table-column>

              <el-table-column
                prop="warehouseName"
                min-width="150"
                label="仓库名称">
              </el-table-column>

              <el-table-column
                width="100"
                prop="pledgeMoney"
                label="抵押金额">
              </el-table-column>
              <el-table-column
                width="100"
                prop="productMoney"
                label="商品金额">
              </el-table-column>

              <el-table-column
                width="160"
                prop="createTime"
                label="应/清/实收数">
                <template slot-scope="scope">
                  <p title="应收数/清点数/实收数" style="text-align: left">{{ scope.row.receivableNumber ? scope.row.receivableNumber : 0 }}/{{ scope.row.applyNumber ? scope.row.applyNumber : 0 }}/{{ scope.row.payableNumber ? scope.row.payableNumber : 0 }}</p>
                </template>
              </el-table-column>
<!--              :class="parseFloat(scope.row.payableMoney) < 0 ? 'error_word':''"-->

              <el-table-column
                width="160"
                prop="createTime"
                label="应/清/实收金额">
                <template slot-scope="scope">
                  <p title="应收金额/清点金额/实收金额" style="text-align: left">{{ scope.row.receivableMoney ? scope.row.receivableMoney : 0 }}/<span :class="parseFloat(scope.row.applyMoney) < 0 ? 'error_word':''">{{ scope.row.applyMoney ? scope.row.applyMoney : 0 }}</span>/<span :class="parseFloat(scope.row.payableMoney) < 0 ? 'error_word':''">{{ scope.row.payableMoney ? scope.row.payableMoney : 0 }}</span></p>
                </template>
              </el-table-column>

              <el-table-column
                width="100"
                label="清点人">
                <template slot-scope="scope">
                  <div>
                    {{scope.row.applyPersonName ? scope.row.applyPersonName : '——'}}
                  </div>
                </template>
              </el-table-column>

              <el-table-column
                width="100"
                label="状态">
                <template slot-scope="scope">
                  <div :style="'color:'+statusColor[scope.row.enable]">
                    {{statusOption[scope.row.enable]}}
                  </div>
                </template>
              </el-table-column>

              <el-table-column
                label="操作"
                fixed="right"
                width="150"
                v-if="btn&&(btn.detail|| btn.check||btn.confirm || btn.delete || btn.changeOrder || btn.assignOrder || btn.confirmChange || btn.confirmSend || btn.senderCheck || btn.manageCheck || btn.chargeOff) ">
                <template slot-scope="scope">
                  <div class="table_btn">
                    <span class="change_info" @click="openPopup(scope.row)" v-if="btn.detail">详情</span>
                    <span class="change_info" @click="changeWare(scope.row)" v-if="btn.changeOrder && scope.row.enable == 2">转单</span>
                    <span class="change_info" @click="hanleAssgin(scope.row)" v-if="btn.assignOrder && (scope.row.enable == 2 || scope.row.enable == 4)">分配</span>
                    <span class="change_info" @click="hanleAgreeChange(scope.row,2)" v-if="btn.confirmSend && (scope.row.enable == 5)">确定配送</span>
                    <span class="change_info delete_btn" @click="hanleAgreeChange(scope.row,3)" v-if="btn.senderCheck && (scope.row.enable == 6)">清点</span>
                    <span class="change_info delete_btn" @click="hanleAgreeChange(scope.row,4)" v-if="btn.manageCheck && (scope.row.enable == 7)">清点</span>
                    <span class="change_info delete_btn" @click="handleChargeOff(scope.row)" v-if="btn.chargeOff && (scope.row.enable == 8)">核销</span>
                    <span class="change_info" @click="hanleAgreeChange(scope.row,1)" v-if="btn.confirmChange && scope.row.enable == 3">接收转单</span>
<!--                    <span class="change_info warming_btn" @click="checkPopup(scope.row)"-->
<!--                          v-if="btn.check && (scope.row.enable === 2)">清点</span>-->
<!--                    <span class="change_info success_btn" @click="confirmItem(scope.row)"-->
<!--                          v-if="btn.confirm && (scope.row.enable === 3)">完成</span>-->
                    <span class="change_info delete_btn" @click="returnDelete(scope.row)" v-if="btn.delete && scope.row.enable === 2">撤销</span>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="record_page">
            <span class="page_count">共<i>{{ totals }}</i>条</span>
            <el-pagination
              @size-change="sizeChange"
              @current-change="getTableInfo"
              background
              :current-page="currentPage"
              :page-sizes="[15, 20, 30, 40]"
              :page-size="pageSize"
              layout="prev, pager, next, sizes,jumper"
              :total="totals">
            </el-pagination>
          </div>
        </div>
        <div class="right_box" v-if="isPop">
          <p class="page_title" >{{ orderNo }}订单详情</p>
          <detail :orderId="orderNo" :isUpdate="update"></detail>
          <p class="page_title">{{ orderNo }}订单日志</p>
          <log :orderId="orderNo" :userId="userId" :isUpdate="update"></log>
        </div>
      </div>

    </div>

    <checkNum v-if="isCheck" :orderNo="checkId" :userId="cuserId" @listenToChild="listenToEdit"></checkNum>
    <changeWarehouse v-if="isChange" :changeId="handleReturnNo" :warehouseId="changeWareId" @listenToChild="listenToEdit"></changeWarehouse>
    <assignOrder v-if="isAssign" :orderId="handleReturnNo" :warehouseId="changeWareId" @listenToChild="listenToEdit"></assignOrder>
    <confiemDetail v-if="isConfirm" :orderId="handleReturnNo" :warehouseId="changeWareId" :userId="doUserId" :isConfirm="doConfirm" @listenToChild="listenToEdit"></confiemDetail>

  </div>
</template>

<script>

import log from '../returnlog/index'
import detail from '../returnDetail/index'
import checkNum from "./checkNum";
import changeWarehouse from "./changeWarehouse";
import assignOrder from "./assignOrder"
import commons from "@/utils/common";
import {chargeOff, createReturnOrder, returnConfirm, returnDelete, returnListData} from "@/api/data/user/productReturn";
import userSelect from '../../../components/user/index.vue'
import {judgeRole} from "@/utils/warehouseAuth";
import confiemDetail from "./detail"
import {getBtn} from "../../../utils/btnAuth";

export default {
  components: {
    log,
    detail,
    checkNum,
    userSelect,
    changeWarehouse,
    assignOrder,
    confiemDetail
  },
  data() {
    return {
      menus:[{name:'申请退货单',id:2},{name:'转单',id:3},{name:'待分配',id:-1},{name:'清点',id:-2},{name:'核销',id:8},{name:'已完成',id:1}],
      status:2,
      mIndex:0,
      returnNo: '',
      userId: '',
      proDate:'',
      warehouseOption:[],
      currentPage: 1,
      pageSize: 15,
      totals: 0,
      loading: false,
      tableInfo: [],
      isPop: false,
      orderId: '',
      orderNo: '',
      checkId: '',
      cuserId: '',
      isCheck: false,
      btn: {},
      update: false,
      warehouseId: '',
      usersId: '',
      user:{},
      isChange:false,
      changeWareId:'',
      isAssign:false,
      handleReturnNo: '',
      isConfirm:false,
      doConfirm:false,
      doUserId:'',
      userType:'',
      statusOption:['','已完成','申请','转单','确认转单','分配','确定配送','清点(配送员)','清点(仓管)'],
      statusColor:['','#DC7E0C','#07CB24','#1FE305','orange','#0F69F9','#409EFF','#7B0CDC','orange']
    }
  },
  mounted() {
    let roleHouse = judgeRole();
    this.warehouseOption = roleHouse.list;
    this.warehouseId = roleHouse.id;
    let str =  window.localStorage.getItem('water_user');
    if (str){
      this.user = JSON.parse(str).loginUser;
    }
    this.usersId = this.$route.query.userId?parseInt(this.$route.query.userId):'';
    this.btn = getBtn();
    this.userType = this.user.type;
    if(this.userType == 6) {
      this.mIndex = 2;
      this.status = -1;
    }
    if (this.btn.query) {
      this.getTableInfo(1);
    }
  },
  methods: {
    chooseTab(index,enable){
      this.mIndex = index;
      this.status = enable;
      this.getTableInfo(1);
    },
    //仓库转单
    changeWare(obj) {
      this.handleReturnNo = obj.returnNo;
      this.changeWareId = obj.warehouseId;
      this.isChange = true;
    },
    //同意换单
    hanleAgreeChange(obj,type) {
      this.isConfirm = true;
      this.doConfirm = type;
      this.doUserId = obj.userId
      this.handleReturnNo = obj.returnNo;
    },
    //分配
    hanleAssgin(obj) {
      this.handleReturnNo = obj.returnNo;
      this.changeWareId = obj.warehouseId;
      this.isAssign = true;
    },

    //生成退货单（测试）
    createOrder() {
      createReturnOrder().then(res => {
        this.getTableInfo(this.currentPage);
      }).catch((e) => {
        this.loading = false;
      });
    },

    //用户商品
    getUserId(e) {
      this.usersId = e;
    },

    // 获取列表信息
    getTableInfo(page) {
      let that = this;
      that.loading = true;
      that.currentPage = page;
      let queryParams = {
        limit: that.pageSize,
        page: page,
        returnNo: that.returnNo,
        warehouseId: that.warehouseId,
        userId: that.usersId,
        startDate:that.proDate?that.proDate[0]:'',
        endDate:that.proDate?that.proDate[1]:'',
        sort:-1,
        enable:that.status
      }

      returnListData(queryParams).then(res => {
        that.tableInfo = res ? res.list : [];
        that.totals = res ? res.count : 0;
        that.loading = false;
      }).catch((e) => {
        that.loading = false;
      });
    },

    // 重置
    resetTable() {
      this.pageSize = 15;
      this.returnNo = '';
      this.usersId = '';
      this.proDate = '';
      this.warehouseId = this.user.type===3?this.warehouseId:''
      this.getTableInfo(1)
    },

    //删除退货单
    returnDelete(obj) {
      let that = this;
      that.$confirm(`确认撤销${obj.returnNo}订单信息`, '提示', {
        confirmButtonText: "确定",
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        return returnDelete(obj.returnNo)
      }).then(() => {
        that.getTableInfo(that.currentPage);
        that.$message.success({
          message:'删除成功！',
          duration:1500
        });
      })
    },

    //核销退货单
    handleChargeOff(obj) {
      let that = this;
      that.$confirm(`确认核销${obj.returnNo}订单信息`, '提示', {
        confirmButtonText: "确定",
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
         chargeOff({returnNo:obj.returnNo}).then((res)=> {
           that.getTableInfo(that.currentPage);
           that.$message.success({
             message:'核销成功！',
             duration:1500
           });
         })
      }).catch(() => {
      })
    },

    // 确认
    confirmItem(obj) {
      let that = this;
      that.$confirm('确定确认' + obj.returnNo + '订单信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let data = {returnNo: obj.returnNo, userId: obj.userId}
        return returnConfirm(data);
      }).then(() => {
        that.getTableInfo(that.currentPage);
        that.$message.success({
          message:'确认成功！',
          duration:1500
        });
      }).catch(() => {
        // console.product('fail')
      });
    },

    // 打开弹窗
    openPopup(obj) {
      this.isPop = true;
      this.orderNo = obj.returnNo;
      this.orderId = obj.returnNo;
      this.userId = obj.userId
    },

    checkPopup(obj) {
      this.isCheck = true;
      this.checkId = obj.returnNo;
      this.cuserId = obj.userId;
    },


    listenToEdit(e) {
      this.isChange = false;
      this.isCheck = false;
      this.isAssign = false;
      this.isConfirm = false;
      if (e) {
        this.getTableInfo(this.currentPage);
        this.update = !this.update;
      }
    },

    formatTime(time) {
      return commons.formatTime(time)
    },

    sizeChange(val) {
      this.pageSize = val;
      this.getTableInfo(1)
    },

    // 设置table标题居中
    tableHeader({row, column, rowIndex, columnIndex}) {
      return 'background:#F0F2F5;color:#111;padding:10px 0;font-size:14px;font-weight:600'
    },
  }
}
</script>

<style scoped>
.flex_box {
  display: flex;
}

.detail_part {
  width: 100%;
}

.left_box {
  width: 60%;
}

.right_box {
  width: 40%;
}

.warming_btn {
  color: #F7AB20;
}

.page_title {
  font-weight: 600;
  padding-left: 20px;
  margin-bottom: 10px;
  font-size: 18px;
}


</style>


